/*================================================================*
        Copyright (C) 2021 All rights reserved, www.hsby.link.
      	文件名称：echo_server.cc
      	创 建 者：汉森伯逸
      	创建日期：2021/12/28
 *================================================================*/
#include "tcp_server.h"
#include "bytearray.h"

class EchoServer : public hsby::TcpServer {
public:
    void ClientHandle(hsby::Socket::Ptr client) override {
        HSBY_LOG_SYSTEM_INFO << "handle client " << *client;
        hsby::ByteArray byte_array;
        while(true) {
            byte_array.Clear();

            std::vector<iovec> iovs;
            byte_array.GetWriteIovecs(iovs, 4096);

            int ret = client->Recv(&iovs[0], iovs.size());
            if (ret == 0) {
                HSBY_LOG_SYSTEM_INFO << "client close " << HSBY_VARS_EXP(client->ToString());
                break;
            }else if (ret < 0) {
                HSBY_LOG_SYSTEM_INFO << "client error " << HSBY_VARS_EXP(client->ToString());
                break;
            }

            if (type_ == 0) {
                HSBY_LOG_SYSTEM_INFO << HSBY_VARS_EXP(byte_array.DataToTextString());
            }else {
                HSBY_LOG_SYSTEM_INFO << HSBY_VARS_EXP(byte_array.DataToHexString());
            }
        }
    }

private:
    int type_ = 0;

public:
    FUNCTION_BUILDER_VAR(Type, type_);
};

void Run() {
    auto server = std::make_shared<EchoServer>();
    if (!server->Init()) {
        HSBY_LOG_SYSTEM_ERROR << "echo server init error";
        return;
    }
    server->Bind(hsby::Ipv4Address::Create("0.0.0.0", 10086));
    server->Start();
}

int main() {
    hsby::IoManager iom(1, "EchoSrv");
    iom.AddTask(Run);
    return 0;
}